package zhupf.config.db;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration("datasourceConfig")
// 设置mybatis 接口的扫描路径，设置引入的sessionFactory 的bean
@MapperScan(basePackages = MysqlDataSourceConfig.DATAPACKAGE,sqlSessionFactoryRef = "SqlSessionFactory")
public class MysqlDataSourceConfig {

    public static final String DATAPACKAGE = "com.zhupf.dao.mysql";

    public static final String MAPPER_SCAN = "classpath:/mapper/*.xml";

    @Value("${spring.datasource.mysql.url}")
    private String url;

    @Value("${spring.datasource.mysql.username}")
    private String username;

    @Value("${spring.datasource.mysql.password}")
    private String password;

    @Value("${spring.datasource.mysql.driver-class-name}")
    private String driverClass;

    @Bean("sqlDatasource")
    public DataSource sqlDatasource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClass);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
//        druidDataSource.setInitialSize(initialSize);
////        druidDataSource.setMinIdle(minIdle);
////        druidDataSource.setMaxActive(maxActive);
////        druidDataSource.setMaxWait(maxWait);
        return druidDataSource;
    }

    // 开启事务
    public DataSourceTransactionManager sqlDataSourceTransctionManager(@Qualifier("sqlDatasource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("sqlDatasource") DataSource dataSource) throws Exception {
        //实例化SqlSessionFactoryBean对象
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //这里是从mybatis的xml路径里加载指定的资源文件);//将解析后返回的Resources数组放在SqlSessionFactoryBean对象里，便于后面进行解析
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
        .getResources(MysqlDataSourceConfig.MAPPER_SCAN));
        return sqlSessionFactoryBean.getObject();
    }

}
